package com.cskaoyan.controller.wx;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.UserInfo;
import com.cskaoyan.realm.MallToken;
import com.cskaoyan.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author
 * @date 2020/12/8 16:52
 */
@Controller
@RequestMapping("wx/auth")
public class LoginController {
    @Autowired
    UserService userService;

    @PostMapping("login")
    public String login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        MallToken wxToken = new MallToken(username, password, "wx");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(wxToken);
        }catch (UnknownAccountException e) {
            return "forward:/wx/auth/fail402";
        } catch (IncorrectCredentialsException e) {
            return "forward:/wx/auth/fail700";
        }
        return "forward:/wx/auth/success";
    }
    @RequestMapping("success")
    @ResponseBody
    public BaseRespVo success(){
        Subject subject = SecurityUtils.getSubject();
        Integer userId = (Integer) subject.getPrincipal();
        UserInfo userInfo = userService.selectUserInfo(userId);
        String token = (String) subject.getSession().getId();
        userInfo.setToken(token);
        System.out.println(userInfo);
        return BaseRespVo.ok(userInfo);
    }

    @RequestMapping("logout")
    @ResponseBody
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }
    @RequestMapping("fail700")
    @ResponseBody
    public BaseRespVo fail700(){

        return BaseRespVo.fail700();
    }

    @RequestMapping("fail402")
    @ResponseBody
    public BaseRespVo fail402(){

        return BaseRespVo.fail402();
    }


}
